<template>
  <div class="editor">
    <tiny-fluent-editor
      v-model="content"
      :data-type="false"
      :data-upgrade="false"
      :image-upload="imageUpload"
    />
  </div>
</template>

<script setup lang="ts">
  import TinyFluentEditor from '@opentiny/vue-fluent-editor';
  import { Message } from '@arco-design/web-vue';
  import { ref, watch } from 'vue';

  const props = defineProps({
    modelValue: {
      type: String,
      default: '',
    },
  });

  // 1. 初始化 content 为父组件传递的 modelValue
  const content = ref(props.modelValue);

  const url = import.meta.env.VITE_API_BASE_URL + 'global/upload';
  const imageUpload = {
    url: url,
    method: 'POST',
    name: 'image',
    withCredentials: true,
    headers: {},
    success: (serverResponse: any, next: any) => {
      // 兼容接口返回格式，优先取 downloadUrl
      const file = serverResponse.data || serverResponse;
      const imgUrl = file.downloadUrl || file.url;
      if (imgUrl) {
        next(imgUrl);
      } else {
        Message.error('图片地址解析失败');
      }
    },
    fail: (serverError: any) => {
      Message.error(serverError.message || '图片上传失败');
    },
  };

  const emits = defineEmits(['update:modelValue']);

  // 2. 监听 content 变化，触发父组件更新
  watch(
    content,
    (newValue) => {
      emits('update:modelValue', newValue);
    },
    { immediate: true }
  );

  // 3. 监听父组件 modelValue 变化，同步更新子组件 content
  watch(
    () => props.modelValue,
    (newVal) => {
      content.value = newVal;
    },
    { immediate: true }
  );
</script>

<style scoped lang="less">
  .auto-tip {
    width: 120px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
</style>
